package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: zcm
 * @CreateTime: 2025-10-14  14:43
 * @Description: Redis 生成全局唯一ID 格式(1bit 符号位 32bit 时间戳 32bit 序列号)
 * @Version: 1.0
 */
@Component
@Slf4j
public class RedisIdWorker {

    // 默认开始时间戳 (2025-1-1)
    private static final long BEGIN_TIMESTAMPS = 1735689600L;
    // ID序列的位数
    private static final int SERIAL_NUM_BIT = 32;
    // Redis
    private final StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix){
        // 1.生成时间戳
        long timestamps = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - BEGIN_TIMESTAMPS;
        // 2.生成序列号
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 3.返回结果
        return timestamps << SERIAL_NUM_BIT | count;
    }
}
